<?php
namespace app\api\service;
use think\Request;
use app\api\model\Supplier;

class SupplierService {

    public function all(){
        return show(1, 'ok', Supplier::all(), 200);
    }

    public function page($page, $size){
        $data 	= Request::instance()->get();
        $where 	= [];

        empty($data['legal']) || $where['legalPerson'] = ['like','%'.$data['legal']];
        empty($data['name']) || $where['name'] = ['like','%'.$data['name']];

        $obj = Supplier::where($where)
        ->paginate($size, false, ['page' => $page]);

        if ($obj->isEmpty()){
            return [];
        }
        return $obj->toArray();
    }

    public function save(){ 
        $param = Request::instance()->param();	//获取参数

        if (!is_numeric($param['id']) || !isset($param['id']))
        {
            // 新增
            $obj = new Supplier;

            try {
                $obj->name = $param['name'];
                $obj->legalPerson = $param['legalPerson'];
                $obj->mobile = $param['mobile'];
                $obj->bank = $param['bank'];
                $obj->isMarket = $param['isMarket'];
                $obj->scope = $param['scope'];

                $obj->province = $param['province'];
                $obj->city = $param['city'];
                $obj->district = $param['district'];
                $obj->detail = $param['detail'];
            }catch(Exption $e) {
                return show(0, '修改失败', [], 200);
            }

            if( $obj->save()){
                return show(1, '新增成功', [], 200);
            }
        }else {
            // 更新
            $obj = Supplier::get($param['id']);
            try {
                $obj->name = $param['name'];
                $obj->legalPerson = $param['legalPerson'];
                $obj->mobile = $param['mobile'];
                $obj->bank = $param['bank'];
                $obj->isMarket = $param['isMarket'];
                $obj->scope = $param['scope'];

                $obj->province = $param['province'];
                $obj->city = $param['city'];
                $obj->district = $param['district'];
                $obj->detail = $param['detail'];
            }catch(Exception $e) {
                return show(0, '修改失败', [], 200);
            }

            // 检测错误
            if( $obj->save()){
                return show(1, '修改成功', [], 200);
            }
        }
        
        return show(0, '修改失败', [], 200);
    }

    public function delete($id){

    	if( Supplier::destroy($id, true) ){
            return show(1, '删除成功', [], 200);
        }
        
        return show(0, '删除失败', [], 200);
    }
}